package com.hh.hhpicturebackend.aop;

import com.hh.hhpicturebackend.annotation.AuthCheck;
import com.hh.hhpicturebackend.exception.BusinessException;
import com.hh.hhpicturebackend.exception.ErrorCode;
import com.hh.hhpicturebackend.model.entity.User;
import com.hh.hhpicturebackend.model.enums.UserRoleEnum;
import com.hh.hhpicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * com.hh.hhpicturebackend.aop
 *
 * @author
 * @version 0.0.1
 * @date 2025/4/29
 **/
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * @param joinPoint
     * @param authCheck
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doIntercept(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 判断用户是否已登录
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 如果不需要权限放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 必须有权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnum == null || userRoleEnum.getValue().compareTo(mustRoleEnum.getValue()) < 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 必须有管理员权限 没有就拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
